package com.wang.helloword;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @BelongsProject: RabbitMqLearn
 * @BelongsPackage: com.wang
 * @Author: wang fei
 * @CreateTime: 2023-02-03  16:49
 * @Description: TODORabbitMq helloword消费者
 * @Version: 1.0
 */
public class MyConsumer {
    public static final String QUEUE_NAME ="my_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        //获取链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.206.130");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("wang");
        connectionFactory.setPassword("123456");
        connectionFactory.setVirtualHost("/test1");
        //获得链接对像
        Connection connection = connectionFactory.newConnection();
        //获得信道
        Channel channel = connection.createChannel();
        //使⽤⾮Lambda的⽅式来消费
//        //创建Consumer对象,指明具体的消息处理程序
//        Consumer consumer = new DefaultConsumer(channel){
//            @Override
//            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                String message = new String(body, "UTF-8");
//                //处理信息,并且进行业务逻辑处理,打印信息
//                System.out.println(message);
//            }
//        };
//        //设置消费者监听queue("my_queue")
//        channel.basicConsume(QUEUE_NAME, true, consumer);

        //Lambda的⽅式来消费
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            //处理信息,并且进行业务逻辑处理,打印信息
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(message);
        };
        //设置消费者监听queue("my_queue")
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumerTag->{});
    }
}

